// import uuid from 'node-uuid';

const uuidv1 = require('node-uuid');
const express = require('express');
const connection = require('../db') // 获取连接实例
const router = express.Router();

const jwt = require("jsonwebtoken")


// 注册用户
router.post("/register", function (req, res){
  console.log('用户注册传参', req.body)
  const userName = req.body.userName
  const nickName = req.body.nickName
  const passWord = req.body.passWord
  if (!userName || !passWord) {
    res.send({
      code: 0,
      msg: "用户名与密码为必传参数...",
    })
    return
  }

  if (userName && passWord) {
    const result = `select * from user where userName = '${userName}'`
    connection.query(result, [userName], (err, results) => {
      if (err) throw err
      if (results.length >= 1) {
        //2、如果有相同用户名，则注册失败，用户名重复
        res.send({ code: 0, msg: "注册失败，用户名重复" })
      } else {
        const id =uuidv1.v1();
        console.log('ID', id);
        const sqlStr = "insert into user(userName,nickName, passWord, id) values(?,?,?,?)"
        connection.query(sqlStr, [userName, nickName, passWord, id], (err, results) => {
          if (err) throw err
          if (results.affectedRows === 1) {
            res.send({ code: 200, msg: "注册成功", data: {id} })
          } else {
            res.send({ code: 0, msg: "注册失败" })
          }
        })
      }
    })
  }
});
// 修改用户信息
router.post("/upData", function (req, res){
  console.log('req', req.body)
  const userName = req.body.userName;
  const passWord = req.body.passWord;
  const userId = req.body.userId;
  const nickname = req.body.nickName;
  if (!userId) {
    res.send({
      code: 0,
      msg: "用户信息获取失败...",
    })
    return
  }

  if (userId) {
    // const result = `UPDATE user SET nickname='${nickname}' where id = '${userId}'`
    const result = `select * from user where id = '${userId}'`
    connection.query(result, [userName], (err, results) => {
      if (err) throw err
      if (results.length <= 0) {
        //2、如果有相同用户名，则注册失败，用户名重复
        res.send({ code: 0, msg: "用户信息获取失败，无法编辑" })
      } else {
        // const sqlStr = "insert into user(userName,passWord, id) values(?,?,?)"
        const sqlStr = `UPDATE user SET nickname='${nickname}' where id = '${userId}'`
        connection.query(sqlStr, (err, results) => {
          console.log('啊啊啊啊啊啊啊啊啊啊', results)
          if (err) throw err
          if (results.affectedRows === 1) {
            res.send({ code: 200, msg: "修改成功", data: {userId} })
          } else {
            res.send({ code: 0, msg: "修改失败" })
          }
        })
      }
    })
  }
});
// 登录
router.post("/login", (req, res) => {
  console.log('login', req.body);
  var userName = req.body.userName
  var passWord = req.body.passWord
  if (!userName || !passWord) {
    res.send({
      code: 0,
      msg: "用户名与密码为必传参数...",
    })
    return
  }
  const sqlStr = "select * from user WHERE userName=? AND passWord=?"
  connection.query(sqlStr, [userName, passWord], (err, result) => {
    console.log('nodeErr', err);
    console.log('nodeResult', result);
    if (err) throw err
    if (result.length > 0) {
      // 生成token
      const token = jwt.sign(
          {
            identity: result[0].identity,
            userName: result[0].userName,
          },
          "secret",
          { expiresIn: "1h" },
      )
      console.log('token', token);
      // console.log('result', );
      const RESULT = JSON.parse(JSON.stringify(result[0]));
      console.log('RESULT', RESULT);
      console.log('result.access', RESULT.access);
      res.send({ code: 200, msg: "登录成功", data: {token: token, access: [RESULT.access], userInfo: RESULT} })

      // 如果没有登录成功，则返回登录失败
    } else {
      // 判断token
      if (req.headers.authorization === undefined || req.headers.authorization === null) {
        if (req.headers.authorization) {
          var token = req.headers.authorization.split(" ")[1] // 获取token
        }
        console.log('错误token', token);
      }
      jwt.verify(token, "secret", (err, decode) => {
        if (err) {
          res.send({ code: 0, msg: "登录失败,账号或密码错误" })
        }
      })
    }
  })
})
router.get("/userInfo", (req, res) => {
  console.log('用户信息', req.query);
  const sqlStr = "select * from user WHERE id=?";
  connection.query(sqlStr, req.query.id, (err, result) => {
    if (err) throw err
    if (result.length > 0) {
      // console.log('result', );
      const RESULT = JSON.parse(JSON.stringify(result[0]));
      console.log('RESULT', RESULT);
      console.log('result.access', RESULT.access);
      res.send({ code: 200, msg: "查询成功", userInfo: RESULT })
    } else {
      res.send({ code: 200, msg: "查询成功", userInfo: {}  })
    }
  })
})
module.exports = router;
